import 'package:flutter/material.dart';
import 'dart:async';
import 'dart:math';
import '../models/morse_character.dart';
import '../services/morse_audio_service.dart';

class TimedPracticePage extends StatefulWidget {
  const TimedPracticePage({super.key});

  @override
  State<TimedPracticePage> createState() => _TimedPracticePageState();
}

class _TimedPracticePageState extends State<TimedPracticePage> {
  final MorseAudioService _audioService = MorseAudioService();
  final Random _random = Random();
  
  String? selectedAnswer;
  bool hasAnswered = false;
  bool isLoading = false;
  bool gameStarted = false;
  bool gameEnded = false;
  
  int score = 0;
  int totalQuestions = 0;
  int timeRemaining = 10; // 每题10秒
  int totalGameTime = 60; // 总游戏时间60秒
  
  Timer? _questionTimer;
  Timer? _gameTimer;
  
  late MorseCharacter currentCharacter;
  late List<String> options;

  @override
  void initState() {
    super.initState();
  }

  @override
  void dispose() {
    _questionTimer?.cancel();
    _gameTimer?.cancel();
    _audioService.stop();
    super.dispose();
  }

  void _startGame() {
    setState(() {
      gameStarted = true;
      gameEnded = false;
      score = 0;
      totalQuestions = 0;
      totalGameTime = 60;
    });

    _generateNewQuestion();
    
    // 开始游戏倒计时
    _gameTimer = Timer.periodic(const Duration(seconds: 1), (timer) {
      setState(() {
        totalGameTime--;
      });
      
      if (totalGameTime <= 0) {
        _endGame();
      }
    });
  }

  void _endGame() {
    setState(() {
      gameEnded = true;
      gameStarted = false;
    });
    
    _questionTimer?.cancel();
    _gameTimer?.cancel();
    _audioService.stop();
  }

  void _resetGame() {
    setState(() {
      gameStarted = false;
      gameEnded = false;
      score = 0;
      totalQuestions = 0;
      timeRemaining = 10;
      totalGameTime = 60;
    });
    
    _questionTimer?.cancel();
    _gameTimer?.cancel();
  }

  void _generateNewQuestion() {
    if (gameEnded) return;
    
    setState(() {
      hasAnswered = false;
      selectedAnswer = null;
      isLoading = false;
      timeRemaining = 10;
    });

    // 随机选择字符
    final availableCharacters = MorseData.letters;
    currentCharacter = availableCharacters[_random.nextInt(availableCharacters.length)];
    
    // 生成选项
    options = _generateOptions(currentCharacter, availableCharacters);
    
    // 自动播放音频
    Future.delayed(const Duration(milliseconds: 500), () {
      if (gameStarted && !gameEnded) {
        _playMorseCode();
      }
    });
    
    // 开始倒计时
    _startQuestionTimer();
  }

  void _startQuestionTimer() {
    _questionTimer?.cancel();
    _questionTimer = Timer.periodic(const Duration(seconds: 1), (timer) {
      setState(() {
        timeRemaining--;
      });
      
      if (timeRemaining <= 0) {
        _timeUp();
      }
    });
  }

  void _timeUp() {
    if (!hasAnswered) {
      setState(() {
        hasAnswered = true;
        totalQuestions++;
      });
      
      _questionTimer?.cancel();
      
      // 1秒后自动进入下一题
      Future.delayed(const Duration(milliseconds: 1000), () {
        if (gameStarted && !gameEnded) {
          _generateNewQuestion();
        }
      });
    }
  }

  List<String> _generateOptions(MorseCharacter correct, List<MorseCharacter> pool) {
    final List<String> result = [correct.character];
    final List<MorseCharacter> others = pool.where((c) => c.character != correct.character).toList();
    
    while (result.length < 4 && others.isNotEmpty) {
      final randomChar = others[_random.nextInt(others.length)];
      if (!result.contains(randomChar.character)) {
        result.add(randomChar.character);
      }
      others.remove(randomChar);
    }
    
    result.shuffle(_random);
    return result;
  }

  Future<void> _playMorseCode() async {
    if (_audioService.isPlaying || hasAnswered || gameEnded) return;
    
    setState(() {
      isLoading = true;
    });
    
    try {
      await _audioService.playCharacter(currentCharacter);
    } finally {
      if (mounted) {
        setState(() {
          isLoading = false;
        });
      }
    }
  }

  void selectAnswer(String answer) {
    if (hasAnswered || gameEnded) return;
    
    setState(() {
      selectedAnswer = answer;
      hasAnswered = true;
      totalQuestions++;
      
      if (answer == currentCharacter.character) {
        score++;
      }
    });

    _questionTimer?.cancel();

    // 短暂延迟后进入下一题
    Future.delayed(const Duration(milliseconds: 800), () {
      if (gameStarted && !gameEnded) {
        _generateNewQuestion();
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    if (!gameStarted && !gameEnded) {
      return _buildStartScreen();
    } else if (gameEnded) {
      return _buildResultScreen();
    } else {
      return _buildGameScreen();
    }
  }

  Widget _buildStartScreen() {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: const Color(0xFF121212),
        elevation: 0,
        leading: IconButton(
          icon: const Icon(Icons.arrow_back, color: Colors.white),
          onPressed: () => Navigator.pop(context),
        ),
        title: const Text(
          'Timed Challenge',
          style: TextStyle(color: Colors.white),
        ),
      ),
      body: Container(
        color: const Color(0xFF121212),
        child: Center(
          child: Padding(
            padding: const EdgeInsets.all(20.0),
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                const Icon(
                  Icons.timer,
                  size: 80,
                  color: Color(0xFF00BFFF),
                ),
                const SizedBox(height: 30),
                const Text(
                  'Timed Challenge',
                  style: TextStyle(
                    color: Colors.white,
                    fontSize: 32,
                    fontWeight: FontWeight.bold,
                  ),
                ),
                const SizedBox(height: 20),
                const Text(
                  'Test your speed and accuracy!',
                  style: TextStyle(
                    color: Color(0xFFAAAAAA),
                    fontSize: 18,
                  ),
                ),
                const SizedBox(height: 40),
                Container(
                  padding: const EdgeInsets.all(20),
                  decoration: BoxDecoration(
                    color: const Color(0xFF1E1E1E),
                    borderRadius: BorderRadius.circular(16),
                  ),
                  child: const Column(
                    children: [
                      Text(
                        'Rules:',
                        style: TextStyle(
                          color: Colors.white,
                          fontSize: 20,
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                      SizedBox(height: 16),
                      Text(
                        '• 60 seconds total game time\n'
                        '• 10 seconds per question\n'
                        '• Audio plays automatically\n'
                        '• Answer as many as you can!',
                        style: TextStyle(
                          color: Color(0xFFAAAAAA),
                          fontSize: 16,
                          height: 1.5,
                        ),
                      ),
                    ],
                  ),
                ),
                const SizedBox(height: 40),
                ElevatedButton(
                  onPressed: _startGame,
                  style: ElevatedButton.styleFrom(
                    backgroundColor: const Color(0xFF00BFFF),
                    foregroundColor: Colors.white,
                    padding: const EdgeInsets.symmetric(horizontal: 40, vertical: 16),
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(12),
                    ),
                  ),
                  child: const Text(
                    'Start Challenge',
                    style: TextStyle(
                      fontSize: 18,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }

  Widget _buildGameScreen() {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: const Color(0xFF121212),
        elevation: 0,
        leading: IconButton(
          icon: const Icon(Icons.close, color: Colors.white),
          onPressed: _endGame,
        ),
        title: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Text(
              'Score: $score/$totalQuestions',
              style: const TextStyle(
                color: Color(0xFF00BFFF),
                fontWeight: FontWeight.bold,
              ),
            ),
            Container(
              padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
              decoration: BoxDecoration(
                color: totalGameTime <= 10 ? const Color(0xFFF44336) : const Color(0xFF1E1E1E),
                borderRadius: BorderRadius.circular(8),
              ),
              child: Text(
                '${totalGameTime}s',
                style: TextStyle(
                  color: totalGameTime <= 10 ? Colors.white : const Color(0xFF00BFFF),
                  fontWeight: FontWeight.bold,
                ),
              ),
            ),
          ],
        ),
      ),
      body: SafeArea(
        child: Padding(
          padding: const EdgeInsets.all(20.0),
          child: Column(
            children: [
              // Question timer
              Container(
                width: double.infinity,
                height: 8,
                decoration: BoxDecoration(
                  color: const Color(0xFF333333),
                  borderRadius: BorderRadius.circular(4),
                ),
                child: FractionallySizedBox(
                  alignment: Alignment.centerLeft,
                  widthFactor: timeRemaining / 10,
                  child: Container(
                    decoration: BoxDecoration(
                      color: timeRemaining <= 3 ? const Color(0xFFF44336) : const Color(0xFF00BFFF),
                      borderRadius: BorderRadius.circular(4),
                    ),
                  ),
                ),
              ),
              
              const SizedBox(height: 20),
              
              Text(
                '$timeRemaining seconds remaining',
                style: TextStyle(
                  color: timeRemaining <= 3 ? const Color(0xFFF44336) : const Color(0xFFAAAAAA),
                  fontSize: 16,
                  fontWeight: FontWeight.bold,
                ),
              ),
              
              const SizedBox(height: 40),
              
              // Audio Player
              GestureDetector(
                onTap: _playMorseCode,
                child: Container(
                  width: 100,
                  height: 100,
                  decoration: BoxDecoration(
                    color: const Color(0xFF1E1E1E),
                    border: Border.all(
                      color: isLoading ? const Color(0xFFFFB74D) : const Color(0xFF00BFFF),
                      width: 3,
                    ),
                    shape: BoxShape.circle,
                  ),
                  child: isLoading
                      ? const CircularProgressIndicator(
                          color: Color(0xFFFFB74D),
                        )
                      : Icon(
                          _audioService.isPlaying ? Icons.volume_up : Icons.replay,
                          size: 40,
                          color: const Color(0xFF00BFFF),
                        ),
                ),
              ),
              
              const SizedBox(height: 60),
              
              // Options Grid
              Expanded(
                child: GridView.count(
                  crossAxisCount: 2,
                  crossAxisSpacing: 15,
                  mainAxisSpacing: 15,
                  children: options.map((option) {
                    Color backgroundColor = const Color(0xFF1E1E1E);
                    Color borderColor = const Color(0xFF333333);
                    
                    if (hasAnswered && selectedAnswer == option) {
                      if (option == currentCharacter.character) {
                        backgroundColor = const Color(0xFF2E7D32);
                        borderColor = const Color(0xFF2E7D32);
                      } else {
                        backgroundColor = const Color(0xFFC62828);
                        borderColor = const Color(0xFFC62828);
                      }
                    } else if (hasAnswered && option == currentCharacter.character) {
                      backgroundColor = const Color(0xFF2E7D32);
                      borderColor = const Color(0xFF2E7D32);
                    }
                    
                    return GestureDetector(
                      onTap: () => selectAnswer(option),
                      child: Container(
                        decoration: BoxDecoration(
                          color: backgroundColor,
                          border: Border.all(color: borderColor, width: 2),
                          borderRadius: BorderRadius.circular(15),
                        ),
                        child: Center(
                          child: Text(
                            option,
                            style: const TextStyle(
                              fontSize: 28,
                              fontWeight: FontWeight.bold,
                              color: Colors.white,
                            ),
                          ),
                        ),
                      ),
                    );
                  }).toList(),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildResultScreen() {
    final accuracy = totalQuestions > 0 ? (score / totalQuestions * 100) : 0;
    
    return Scaffold(
      appBar: AppBar(
        backgroundColor: const Color(0xFF121212),
        elevation: 0,
        leading: IconButton(
          icon: const Icon(Icons.arrow_back, color: Colors.white),
          onPressed: () => Navigator.pop(context),
        ),
        title: const Text(
          'Challenge Complete',
          style: TextStyle(color: Colors.white),
        ),
      ),
      body: Container(
        color: const Color(0xFF121212),
        child: Center(
          child: Padding(
            padding: const EdgeInsets.all(20.0),
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Icon(
                  accuracy >= 80 ? Icons.emoji_events : Icons.thumb_up,
                  size: 80,
                  color: accuracy >= 80 ? const Color(0xFFFFD700) : const Color(0xFF00BFFF),
                ),
                const SizedBox(height: 30),
                Text(
                  accuracy >= 80 ? 'Excellent!' : accuracy >= 60 ? 'Good Job!' : 'Keep Practicing!',
                  style: const TextStyle(
                    color: Colors.white,
                    fontSize: 32,
                    fontWeight: FontWeight.bold,
                  ),
                ),
                const SizedBox(height: 40),
                Container(
                  padding: const EdgeInsets.all(24),
                  decoration: BoxDecoration(
                    color: const Color(0xFF1E1E1E),
                    borderRadius: BorderRadius.circular(16),
                  ),
                  child: Column(
                    children: [
                      Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          const Text(
                            'Score:',
                            style: TextStyle(
                              color: Color(0xFFAAAAAA),
                              fontSize: 18,
                            ),
                          ),
                          Text(
                            '$score / $totalQuestions',
                            style: const TextStyle(
                              color: Colors.white,
                              fontSize: 18,
                              fontWeight: FontWeight.bold,
                            ),
                          ),
                        ],
                      ),
                      const SizedBox(height: 16),
                      Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          const Text(
                            'Accuracy:',
                            style: TextStyle(
                              color: Color(0xFFAAAAAA),
                              fontSize: 18,
                            ),
                          ),
                          Text(
                            '${accuracy.toStringAsFixed(1)}%',
                            style: const TextStyle(
                              color: Color(0xFF00BFFF),
                              fontSize: 18,
                              fontWeight: FontWeight.bold,
                            ),
                          ),
                        ],
                      ),
                    ],
                  ),
                ),
                const SizedBox(height: 40),
                Row(
                  children: [
                    Expanded(
                      child: ElevatedButton(
                        onPressed: _resetGame,
                        style: ElevatedButton.styleFrom(
                          backgroundColor: const Color(0xFF1E1E1E),
                          foregroundColor: Colors.white,
                          padding: const EdgeInsets.symmetric(vertical: 16),
                          shape: RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(12),
                          ),
                        ),
                        child: const Text(
                          'Try Again',
                          style: TextStyle(fontSize: 16),
                        ),
                      ),
                    ),
                    const SizedBox(width: 16),
                    Expanded(
                      child: ElevatedButton(
                        onPressed: () => Navigator.pop(context),
                        style: ElevatedButton.styleFrom(
                          backgroundColor: const Color(0xFF00BFFF),
                          foregroundColor: Colors.white,
                          padding: const EdgeInsets.symmetric(vertical: 16),
                          shape: RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(12),
                          ),
                        ),
                        child: const Text(
                          'Back to Menu',
                          style: TextStyle(fontSize: 16),
                        ),
                      ),
                    ),
                  ],
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }
}
